package com.luotao.test.netty.jsonnio;

/**
 * Created by IntelliJ IDEA.
 * User: luotao
 * Date: 12-5-30
 * Time: 01:34
 */


import com.luotao.devp.base.socket.model.BaseRequest;
import com.luotao.devp.base.test.TesterConcurrent;
import com.luotao.devp.base.utils.App;
import com.luotao.test.netty.model.req.ReqTrade;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.springframework.context.ApplicationContext;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

/**
 * Created by IntelliJ IDEA.
 * User: luotao
 * Date: 12-5-29
 * Time: 20:39
 */
public class MessageClient {

    public static List<Channel> channelList = new ArrayList<Channel>();

    public static ChannelFactory factory = null;

    public static void doRequest() {


        //     factory.releaseExternalResources();
    }

    public static void main(String[] args) throws Exception {
        ApplicationContext app = App.getApp("spring/app-socket-client.xml");
        BaseRequest baseRequest = (BaseRequest) app.getBean("baseRequest");

        factory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), 8);
        final ClientBootstrap bootstrap = new ClientBootstrap(factory);

        ClientMessageFactory fac = new ClientMessageFactory();

        bootstrap.setPipelineFactory(fac);

        bootstrap.setOption("tcpNoDelay", true);
        bootstrap.setOption("keepAlive", true);

        TesterConcurrent.runLoopInner(2, new TesterConcurrent.ITestable() {
            @Override
            public void execute(long index, long threadid, int loop_index) throws Exception {

                ReqTrade reqTrade = new ReqTrade();
                reqTrade.setUsername("luotao" + index);
                reqTrade.setPassword("123");
                String s = com.alibaba.fastjson.JSON.toJSONString(reqTrade);
                byte[] request = s.getBytes();
                ChannelBuffer buf = ChannelBuffers.buffer(4 + request.length);//(2)
                buf.writeInt(reqTrade.getCommand());
                buf.writeBytes(s.getBytes());


                final ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 8080));
                final Channel channel = future.awaitUninterruptibly().getChannel();

                if (!future.isSuccess()) {
                    future.getCause().printStackTrace();
                    bootstrap.releaseExternalResources();

                }

                ChannelFuture lastWriteFuture = channel.write(buf);

                // If user typed the 'bye' command, wait until the server closes
                // the connection.
                channel.getCloseFuture().awaitUninterruptibly();

                // Wait until all messages are flushed before closing the channel.
                if (lastWriteFuture != null) {
                    lastWriteFuture.awaitUninterruptibly();
                }


                // Close the connection.  Make sure the close operation ends because
                // all I/O operations are asynchronous in Netty.
                channel.close().awaitUninterruptibly();
                System.out.println("receive sucess");
                // Shut down all thread pools to exit.
//
            }
        }, 2);
       bootstrap.releaseExternalResources();

    }
}